package SIM_base;

#Copyright 2006 - 2008 Bernard van de Koppel
#This file is part of Sipman
#Sipman is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Sipman is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Sipman.  If not, see <http://www.gnu.org/licenses/>.
#
use strict;
require Exporter;
use SIM_settings;
use Net::DNS;
use CGI qw(param);


our @ISA 	= ("Exporter");
our @EXPORT	= qw( catFileLine catFile 
                      printFileLine touchFile removeOldEntries
                      testUpdFile testNameStrict testMkDir updateNodeStatus updateManType formatIntName shortHostname
                      getIpDir getDevDir getNodeColor printDate printDebug testIfIp testBetween testIfMac getLogMac
                      oidToMac dotFormatted
		      logLine getDnsPtr getAreccord testDnsName make_hex_string longIp
                      calcIpNet convertBinIp testFileAge
                     );
our @VERSION	= 0.01;			# version number

# include variabeles to be used over the various modules here.
#
#

#my $ipDatabaseDir = $ENV{'SIM_IPDATAB'};

sub formatIntName {
  my $intName = $_[0];
  my $modIntName = lc $intName;
  $modIntName =~ s#/#-#g;
  $modIntName =~ s#\.#_#g;
  $modIntName =~ s# ##g;
  $modIntName =~ s#:#-#g;
  return $modIntName;
}

sub dotFormatted
{
  # sub to create formatting of numbers
  # found on www.willmaster.com
  my $delimiter = '.'; # replace comma if desired
  my($n,$d) = split /\./,shift,2;
  my @a = ();
  while($n =~ /\d\d\d\d/)
  {
    $n =~ s/(\d\d\d)$//;
    unshift @a,$1;
  }
  unshift @a,$n;
  $n = join $delimiter,@a;
  $n = "$n\.$d" if $d =~ /\d/;
  return $n;
}


sub oidToMac {
  # this sub will convert the oid to an mac
  my $oid = $_[0];
  my ( $mac );
  my @info = split('\.', $oid);
  my $num = 0;
  foreach my $entry (@info) {
    my $hexPart = sprintf("%02x", $entry);
    if ( $num eq 0 ) {
      $mac = $hexPart;
    } else {
      $mac = "$mac:$hexPart";
    }
    $num++;
  }
  return("$mac");
}


sub testFileAge {
  my $file = $_[0];
  if ( -f $file ) {
    my $write_secs = (stat($file))[9];
    my $elapsed = (time) - $write_secs;
    my $daysElapsed = $elapsed / 86400;
    $daysElapsed = sprintf('%.0f', $daysElapsed);
    print(" $daysElapsed ");
    return $daysElapsed;
  }
}

sub testBetween {
  my $ipAddr = "$_[0]";
  my $start = "$_[1]";
  my $stop = "$_[2]";
  my $result = "";
  my @ipTest = split('\.', $ipAddr);
  my @ipStart = split('\.', $start);
  my @ipStop = split('\.', $stop);
  foreach my $item (0 .. 3) {
    printDebug("1", " item=$item ipTest=$ipTest[$item]. ipStart=$ipStart[$item]. ipStop=$ipStop[$item].");
    if (( $ipTest[$item] < $ipStart[$item] ) or ( $ipTest[$item] > $ipStop[$item] )) {
      printDebug("1" , "testBetween: break item=$item ipTest=$ipTest[$item]. ipStart=$ipStart[$item]. ipStop=$ipStop[$item].");
      last;
    } elsif (( $ipTest[$item] > $ipStart[$item] ) or ( $ipTest[$item] < $ipStop[$item] )) {
      printDebug("1" , "testBetween: range item=$item ipTest=$ipTest[$item]. ipStart=$ipStart[$item]. ipStop=$ipStop[$item].");
      $result = "xxxx";
      last;
    } else {
      $result = "x$result";
    }
  }
  return $result;
}



sub getLogMac {
  my $ipAddr = $_[0];
  my $ipDir = getIpDir($ipAddr);
  my $logMac;
  if ( -d $ipDir ) {
    if ( -f "$ipDir/firstmac.txt" ) {
      $logMac = catFileLine("$ipDir/firstmac.txt");
    } elsif ( -f "$ipDir/dhcpmacaddr.txt" ) {
      $logMac = catFileLine("$ipDir/dhcpmacaddr.txt");
    } elsif ( -f "$ipDir/arpmac.txt" ) {
      $logMac = catFileLine("$ipDir/arpmac.txt");
    }
    return $logMac;
  }
}

sub testIfMac {
  # this sub will test / convert the various mac syntaxes to an Sipman syntax.
  my $testMac = lc($_[0]);
  my $macReturn;
  if ( $testMac =~ /^([0-9a-f]{2}):([0-9a-f]{2}):([0-9a-f]{2}):([0-9a-f]{2}):([0-9a-f]{2}):([0-9a-f]{2})$/i) {
    # standard sipman / dhcp mac notation
    return $testMac;
  } elsif ( $testMac =~ /^([0-9a-f]{2})-([0-9a-f]{2})-([0-9a-f]{2})-([0-9a-f]{2})-([0-9a-f]{2})-([0-9a-f]{2})$/i) {
    # cisco acs notation
    my @macArr = split('-', $testMac);
    my $returnMac = join(':', @macArr);
  } elsif ( $testMac =~ /^([0-9a-f]{4})[.]([0-9a-f]{4})[.]([0-9a-f]{4})$/i) {
    # mac notation used by cisco
    my @macArr = ();
    $macArr[0] = substr($testMac,0,2);
    $macArr[1] = substr($testMac,2,2);
    $macArr[2] = substr($testMac,5,2);
    $macArr[3] = substr($testMac,7,2);
    $macArr[4] = substr($testMac,10,2);
    $macArr[5] = substr($testMac,12,2);
    my $returnMac = join(':', @macArr);
#   print("returnMac=\"$returnMac\" ");
    return $returnMac;
  } else {
    return "noMac";
  }
}

sub removeOldEntries {
  my $searchStr = "$_[0]";
  my $ageSecs = "$_[1]";
  if ( "$ageSecs" eq "" ) { $ageSecs = 300; }
  my @fileList = <$searchStr*>;
  my $now = time;
  foreach my $entry (@fileList) {
    my $time = (stat $entry)[9];
    my $elapsed = $now - $time;
    if ( "$elapsed" > "$ageSecs" ) {
      printDebug("0", "Removing old defs $entry");
      unlink $entry;
    }
  }
}


sub touchFile {
  my $file = "$_[0]";
  open(FH,">$file") or die "Can't create $file: $!";
  close(FH);
}


sub convertBinIp {
   # convert bin ip returned from cdp-neighbours to an real ip.
   #my $str = unpack "H*", shift @_;
   my $str = unpack "H*", shift @_;
   $str =~ s/(..)/ $1/g;
   my ( $hex1, $hex2, $hex3, $hex4 ) = split(' ', $str);;
   my $oct1 = hex($hex1);
   my $oct2 = hex($hex2);
   my $oct3 = hex($hex3);
   my $oct4 = hex($hex4);
   return "$oct1.$oct2.$oct3.$oct4";
}

sub calcIpNet {
  my $ipAddr = "$_[0]";
  my $netMask = "$_[1]";
  my $option = "$_[2]";

  my @addrarr=split(/\./,$ipAddr);
  my ( $ipaddress ) = unpack( "N", pack( "C4",@addrarr ) );
  my @maskarr=split(/\./,$netMask);
  my ( $netmask ) = unpack( "N", pack( "C4",@maskarr ) );

  # Calculate network address by logical AND operation of addr & netmask
  # and convert network address to IP address format
  my $netadd = ( $ipaddress & $netmask );
  my @netarr=unpack( "C4", pack( "N",$netadd ) );
  my $netaddress=join(".",@netarr);

  # Calculate broadcase address by inverting the netmask
  # and do a logical or with network address
  my $bcast = ( $ipaddress & $netmask ) + ( ~ $netmask );
  my @bcastarr=unpack( "C4", pack( "N",$bcast ) ) ;
  my $broadcast=join(".",@bcastarr);
  if ( $option eq "broadcast" ) {
    return $broadcast;
  } else {
    return $netaddress;
  }
}


sub longIp {
  my $ipAddr = "$_[0]";
  my ( $ip1, $ip2, $ip3, $ip4 ) = split('\.', $ipAddr);
  my $longIp = sprintf("%03d.%03d.%03d.%03d", $ip1, $ip2, $ip3, $ip4);
  return $longIp;
}


sub make_hex_string {
   my $str = unpack "H*", shift @_;
   $str =~ s/(..)/:$1/g;
   $str =~ s/^://;
   $str;
}


sub testDnsName {
  my $input = "$_[0]";
  my @skipList = split(' ', $SIMparam{'SIMskipDnsNames'});
  foreach my $name (@skipList) {
    if ( "$name" eq "$input" ) {
      $input = "";
      last;
    }
  }
  $input =~ tr/A-Z/a-z/;
  $input =~ s/_/-/g;
  $input =~ s/[^a-z0-9\.\-]//g;
  return $input;
}

sub getDnsPtr {
  # return a single IpName
  my $ipAddr = "$_[0]";
  my $inaddrSrvList = "$_[1]";
  my @nameServers;
  printDebug( "0", "getDnsPtr: ipAddr: $ipAddr, inaddrSrvList: $inaddrSrvList.");
  if ( "$inaddrSrvList" ne "" ) {
    # use the not default nameservers if specified.
    my @inaddrServers = split(' ', $inaddrSrvList);
    foreach my $entry (@inaddrServers) {
      my $test = testIfIp( $entry );
      if ( "$test" eq "oke" ) {
        push(@nameServers, $entry);
      } else {
        printDebug( "0", "getDnsPtr: $entry not a nameserver.");
      }
    }
  }
  foreach my $entry (@nameServers) {
    print("ns:$entry. ");
  }
  if ( "$nameServers[0]" eq "" ) {
    @nameServers = split(' ', $SIMparam{'SIMsystemDnsServers'});
  }
  if ( "$nameServers[0]" ne "" ) {
    my $res = Net::DNS::Resolver->new(
      nameservers => [ @nameServers ],
      recurse     => 0,
      debug       => 1,
    );
    my $answer = $res->search($ipAddr);
    if ($answer) {
      foreach my $rr ($answer->answer) {
        printDebug( "0", "getDnsPtr: $rr->type, answer: $rr->ptrdname.");
        next unless $rr->type eq "PTR";
        my $answer = $rr->ptrdname;
        return $answer;
        last;
      }
    } else {
      print "query failed: ", $res->errorstring, "\n";
    }
  } else {
    printDebug( "0", "getDnsPtr: no useable nameservers defined.");
  }
}


sub getAreccord {
  my $dnsName = "$_[0]";
  my $inaddrSrvList = "$_[1]";
  my $testIpAddr = "$_[2]";
# $dnsName = "$dnsName.";
  if ( "$inaddrSrvList" eq "" ) { $inaddrSrvList = "127.0.0.1"; }
  my $return = "";
  my $nameServers;
  if ( "$inaddrSrvList" ne "" ) {
    my @inaddrServers = split(' ', $inaddrSrvList);
    foreach my $entry (@inaddrServers) {
      my $test = testIfIp( $entry );
      if ( "$test" eq "oke" ) {
#       print("serverIp: $entry ");
        if ( $nameServers eq "" ) {
          $nameServers = $entry;
        } else {
          $nameServers = "$nameServers $entry";
        }
      }
    }
    if ( "$nameServers" ne "" ) {
#     printDebug( "0", "getAreccord: nameServers: $nameServers.");
    }
  }
# my $ares = Net::DNS::Resolver->new( nameservers => [qw($nameServers)], );
  # problems resolving A reccords with dns servers defined.
  my $ares = Net::DNS::Resolver->new;
  my $answer = $ares->search($dnsName);
  if ($answer) {
    foreach my $rr ($answer->answer) {
      next unless $rr->type eq "A";
      my $result = $rr->address;
#     printDebug( "0", "getAreccord: result = $result.");
      if ( "$result" eq "$testIpAddr" ) {
        $return = "oke";
	last;
      } else {
        $return = $result;
      }
#     print("result: $result ");
    }
# } else {
#   print "query failed: ", $ares->errorstring, "\n";
  }
  return $return;
}

# duplicate routine, can be removed if redundant
sub testIfIp2 {
  #Test if an ip address looks like one. 
  my $ipAddr = "$_[0]";
  my $testIpAddr = $ipAddr;
  $testIpAddr =~ tr#0-9[\.]#A#cds;
# print("ip=$testIpAddr");
  my ( $ip1, $ip2, $ip3, $ip4, $rest ) = split('\.', $testIpAddr);
# print("ip1=$ip1, ip2=$ip2, ip3=$ip3, ip4=$ip4, ");
  if ( "$rest" ne "" ) {
    return "Oops, to many dots.";
  } elsif ( "$ip4" eq "" ) {
    return "not four parts";
   } elsif (( "$ip1" < "0" ) or ( "$ip1" > "223" )) {
    return "ip1";
   } elsif (( "$ip2" < "0" ) or ( "$ip2" > "255" )) {
    return "ip2";
   } elsif (( "$ip3" < "0" ) or ( "$ip3" > "255" )) {
    return "ip3";
   } elsif (( "$ip4" < "0" ) or ( "$ip4" > "255" )) {
    return "ip4";
   } elsif ( "$ipAddr" eq "$testIpAddr" ) {
    return "oke";
   } else {
    return "problem with $ipAddr ($testIpAddr)";
   }
}

sub printDebug {
  my $level = "$_[0]";
  my $string = "$_[1]";
  if (( "$level" eq "0" ) or ( "$debugging" eq "yes" )) {
    my $now = time;
    my $dateStr = printDate( $now, "hhmmss" );
    print("<BR>   <B>$dateStr: $string</B> ");
  }
}

sub updateNodeStatus {
  my $ipAddr = "$_[0]";
  my $name = "$_[1]";
  my $status = "$_[2]";
  my $logStatus = lc $status;
  my $ipDir = getIpDir( $ipAddr );
  my $currInfo = catFileLine("$ipDir/pollstatus.txt");
  my ( $oldDate, $oldStatus ) = split(' ', $currInfo);
  if (( $oldStatus eq "Unmanaged" ) and (( $status ne "Managed" ) and ( $status ne "Confirmed" ))) {
    printDebug( 0, "Not updating unmanaged node $ipAddr ($name), to $status.");
  } elsif ( $status ne $oldStatus ) {
    # check for nodes that go down, if they have not gone up the last 10 minutes, and were confirmed before that.
    # sometimes nodes are reported up, which are firewalled ( seen in fping on AIX" ). This will prevent triggering
    # errors in such a case for monitored nodes.
    my $lastStatusFile = "$ipDir/lastStatus";
    if ( $status eq "Up" ) {
      printFileLine($lastStatusFile,"quiet","$oldStatus");
    } elsif ( $status eq "Down" ) {
      if ( -f $lastStatusFile ) {
        my $write_secs = (stat($lastStatusFile))[9];
        my $elapsed = (time) - $write_secs;
        if ( $elapsed > "600" ) {
          unlink $lastStatusFile;
        } else {
          my $lastStatus = catFileLine("$ipDir/lastStatus");
          if ( $lastStatus eq "Confirmed" ) {
            $status = $lastStatus;
          }
        }
      }
    }
    my $statusDate = printDate( time, "logdate" );
    my $manType = catFileLine("$ipDir/managementtype.txt");
    if (( $status eq "Down" ) and ( $manType eq "unstable" )) {
      $status = "Confirmed";
      logLine("$ipAddr","$logStatus","Node-Confirmed","$ipAddr changed status to $status (manType is unstable) by $name ($oldStatus $oldDate).");
    } else {
      logLine("$ipAddr","$logStatus","Node-$logStatus","$ipAddr changed status to $status by $name ($oldStatus $oldDate).");
    }
    printFileLine("$ipDir/pollstatus.txt", "quiet", "$statusDate $status");
  }
}

sub updateManType {
  my $ipAddr = "$_[0]";
  my $name = "$_[1]";
  my $manType = "$_[2]";
  my $ipDir = getIpDir( $ipAddr );
  my $oldManType = catFileLine("$ipDir/managementtype.txt");
  if ( $manType ne $oldManType ) {
    my $statusDate = printDate( time, "logdate" );
    logLine("$ipAddr","system","Mod-manType","$ipAddr changed managementType to $manType by $name ($oldManType).");
    printFileLine("$ipDir/managementtype.txt", "managementType $ipAddr", "$manType");
  }
}


sub printDate {
  my $timestamp = "$_[0]";
  my $paramType = "$_[1]";
  my $type = "default";
  if (  "$paramType" ne "" ) {
    $type = $paramType;
  }
  my ($sec,$min,$hour,$mday,$mon,$jaar,$wday,$yday,$isdst) = localtime($timestamp);
  my @z2 = ('00' .. '60');
  $mon++;
  $jaar = $jaar + 1900;
  if ( $type eq "yyyymmdd" ) {
    return("$jaar\-$z2[$mon]\-$z2[$mday]");
  } elsif ( $type eq "hhmmss" ) {
    return("$z2[$hour]\:$z2[$min]\:$z2[$sec]");
  } elsif ( $type eq "logdate" ) {
    return("$jaar\-$z2[$mon]\-$z2[$mday]_$z2[$hour]\:$z2[$min]\:$z2[$sec]");
  } elsif ( $type eq "wday" ) {
    return("$wday");
  } else {
    return("$jaar\-$z2[$mon]\-$z2[$mday] $z2[$hour]\:$z2[$min]\:$z2[$sec]");
  }
}


sub catFileLine {
  my $outPut = "";
  my ($file) = $_[0];
  my ($altern) = $_[1];
  if (( -f $file ) and ( -r $file )) {
    open FH, $file;
    $outPut = <FH>;
    close FH;
    chomp($outPut);  # remove the newline
  }
  if ( "$outPut" eq "" ) {
    $outPut = $altern;
  }
  return $outPut;
}

sub catFile {
  my $file = "$_[0]";
  my $return = "$_[1]";
  open(INFO, $file);
  my @lines = <INFO>;
  close(INFO);
  if ( $return eq "return" ) {
    my $info = join('<BR>', @lines);
    return $info;
  } else {
    print @lines;
  }
}

sub testMkDir {
  my $dirName = "$_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
  if ( ! -d $dirName ) {
    print("Oops, could not create $dirName, exiting....");
    exit;
  }
}

sub printFileLine {
  my $file = "$_[0]";
  my $varName = "$_[1]";
  my $rest = $_[2];
  my $oldVal = catFileLine($file);
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if (( -f $file ) and ( $oldVal eq $rest )) {
    # update the access time (= touch), if a file is unchanged.
    my $now = time;
    if ( $varName ne "noTouch" ) {
      utime $now, $now, $file;
    }
  } else {
    if ( "$rest" eq "" ) {
      # remove file if it exists (don't display message if it doesn't.).
      if ( -f $file ) {
        unlink ($file);
        print("$varName is verwijderd, oud:$oldVal<BR>");
      }
    } elsif ( "$varName" eq "append" ) {
#     print("writing to $file<BR>.");
      open(OUT, ">>$file") || die "cannot append $file: $!";
      print OUT $rest;
      close(OUT);
    } else {
      if (( "$varName" ne "quiet" ) and ( $varName ne "noTouch" )) {
        if ( ! -f $file ) {
          print("$varName is created, new:$rest<BR>");
        } else {
          print("$varName is changed, old:$oldVal new:$rest<BR>");
        }
      }
      open(OUT, ">$file") || die "cannot create $file: $!";
      print OUT $rest;
      close(OUT);
    }
  }
}

sub testUpdFile {
  my $fileName = $_[0];
  my $httpParam = $_[1];
  my $descr = $_[2];
  my $oldVal = catFileLine "$fileName";
  my $newVal = param("$httpParam");
# printDebug( 0, "testUpdFile: testing $httpParam.");
  if ( $newVal eq "\." ) {
    print("Removing $oldVal from $descr.\n");
    unlink($fileName);
    # set the return value
    $oldVal = "";
  } elsif (( $oldVal ne $newVal ) and ( $newVal ne "" )) {
    printFileLine ("$fileName", "$descr", "$newVal");
    # set the return value
    $oldVal = $newVal;
  }
  return $oldVal;
}

sub testNameStrict {
  my ($testname) = $_[0];
  my ($type) = $_[1];
  if ( "$type" eq "yyyymmdd" ) {
    $testname =~ tr#0-9#A#cds;
    my $length = length("$testname");
    if ( "$length" eq "8" ) {
      my $yyyy = substr($testname,0,4);
      my $mm = substr($testname,4,2);
      my $dd = substr($testname,6,2);
      #$mm = $mm * 1;
      if (( "$yyyy" lt "2000" ) or ( "$yyyy" gt "2020" )) {
        print("Oops, geen geldig jaar gevonden ($yyyy)");
        $testname = "";
      } elsif (( "$mm" lt "0" ) or ( "$mm" gt "13" )) {
        print("Oops, geen geldige maand gevonden ($mm)");
        $testname = "";
      } elsif (( "$dd" le "0" ) or ( "$dd" gt "31" )) {
        print("Oops, geen geldige dag gevonden ($dd)");
        $testname = "";
      }
    } else {
      $testname = "";
    }
  } elsif ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } elsif ( "$type" eq "email" ) {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-][\_]#A#cds;
  } else {
    #print ("testname=$testname");
    $testname =~ tr#a-zA-Z0-9#A#cds;
  }
  return $testname;
}

sub getIpDir {
  my $workDir = "$_[0]";
  $workDir =~ s#\.#/#g;
  $workDir = "$ipDatabaseDir/$workDir";
  return $workDir;
}

sub shortHostname {
  my $testName = "$_[0]";
  $testName = lc($testName);
  my ( $shortName, $dummy ) = split('\.', $testName);
  if ( $shortName eq "" ) {
    $shortName = "none";
  }
  return($shortName);
}
sub getDevDir {
  my $ipAddr = "$_[0]";
  my $vendor = "none";
  my $shortName = "none";
  my $dummy;
  my $ipDir = getIpDir($ipAddr);
  if ( -f "$ipDir/vendor" ) {
    $vendor = catFileLine("$ipDir/vendor");
    my $hostname = catFileLine("$ipDir/hostname.txt");
    ( $shortName, $dummy ) = split('\.', $hostname);
  }

  return( "$SIMparam{'SIMdeviceDir'}/$vendor/$shortName");
}

sub getNodeColor {
  my $ipAddr = "$_[0]";
  my $ipDir = getIpDir( $ipAddr );
  my %ipColor = ();
  $ipColor{ 'Up' } = '#99EE99';
  $ipColor{ 'Down' } = '#FF6600';
  $ipColor{ 'Unmanaged' } = '#33FFFF';
  $ipColor{ 'Confirmed' } = '#DDA0DD';
  $ipColor{ 'New' } = 'yellow';
  my $pollInfo = catFileLine("$ipDir/pollstatus.txt");
  my ( $rest, $pollStatus ) = split(" ", $pollInfo);
  return $ipColor{ $pollStatus};
}

sub testIfIp {
  my $ipAddr = "$_[0]";
  my $testIpAddr = $ipAddr;
  $testIpAddr =~ tr#0-9[\.]#A#cds;
# print("ip=$testIpAddr");
  my ( $ip1, $ip2, $ip3, $ip4, $rest ) = split('\.', $testIpAddr);
# print("ip1=$ip1, ip2=$ip2, ip3=$ip3, ip4=$ip4, ");
  if ( "$rest" ne "" ) {
    return "Oops, to many dots.";
  } elsif ( "$ip4" eq "" ) {
    return "not four parts";
   } elsif (( "$ip1" < "1" ) or ( "$ip1" > "223" )) {
    return "ip1";
   } elsif (( "$ip2" < "0" ) or ( "$ip2" > "255" )) {
    return "ip2";
   } elsif (( "$ip3" < "0" ) or ( "$ip3" > "255" )) {
    return "ip3";
   } elsif (( "$ip4" < "0" ) or ( "$ip4" > "255" )) {
    return "ip4";
   } elsif ( "$ipAddr" eq "$testIpAddr" ) {
    return "oke";
   } else {
    return "problem with $ipAddr ($testIpAddr)";
   }
}

sub logLine {
  my $ipAddr = "$_[0]";
  my $errorType = "$_[1]";
  my $errorName = "$_[2]";
  my $errorMessage = "$_[3]";
  #remoteUser
  my ($dnsName);
  my $ipDir = getIpDir( $ipAddr );
  if ( -f "$ipDir/dnsname.txt" ) {
    my $info = catFileLine("$ipDir/dnsname.txt");
    my ( $type, $hostname, $domain ) = split(' ', $info);
    $dnsName = "$hostname.$domain";
  } else {
    $dnsName = $ipAddr;
  }
  my $nowdate = printDate( time, "default" );
  my $errMessage = "$nowdate $ipAddr $dnsName $errorType $errorName, $errorMessage\n";
  print("Logging: $errMessage");
  if (( -d $ipDir ) and ( "$ipAddr" ne "" )) {
    # print the error to the ip log.
    printFileLine("$ipDir/messages","append","$errMessage");
    my $logMac = &getLogMac($ipAddr);
    if ( "$logMac" ne "" ) {
      # print the error to the mac log.
      if ( -d "$macDatabaseDir/$logMac" ) {
        printFileLine("$macDatabaseDir/$logMac/messages","append","$errMessage");
      }
    }
  }
  if ( -d $SIMparam{'SIMmessagesDir'} ) {
    # print the error to the general log file
    my $nodeType;
    printFileLine("$SIMparam{'SIMmessagesDir'}/messages-all-log","append","$errMessage");
    if ( -f "$ipDir/nodetype.txt" ) {
      # print the error to the nodetype specific log file
      $nodeType = catFileLine("$ipDir/nodetype.txt");
      printFileLine("$SIMparam{'SIMmessagesDir'}/messages-$nodeType-log","append","$errMessage");
    }
    printDebug("1", "errorType=$errorType, errorAllert=$errorAllert{$errorType} nodeManType=$nodeManType{$nodeType}  ");
    if (( "$errorType" eq "note" ) or ( "$errorType" eq "hwChange" )) {
      printFileLine("$SIMparam{'SIMmessagesDir'}/messages-$errorType-log","append","$errMessage");
    }
    if ((( "$errorAllert{$errorType}" eq "error" ) or ( "$errorAllert{$errorType}" eq "email" ) or ( "$errorAllert{$errorType}" eq "sms" )) and
        ( "$nodeManType{$nodeType}" eq "critical" )) {
      # print special error messages to the error logfile (for the monitor page).
      printFileLine("$SIMparam{'SIMmessagesDir'}/messages-error-log","append","$errMessage");
      if (( "$errorAllert{$errorType}" eq "email" ) or ( "$errorAllert{$errorType}" eq "sms" )) {
        my ( $date, $time, $ipAddr, $dnsName, $type, $message ) = split(' ', $errMessage, 6);
	printFileLine("$SIMparam{'SIMtmpDir'}/syslogAction-$errorAllert{$errorType}-$dnsName","append","($errorAllert{$errorType}) $dnsName $date $time $message");
      }
    }
  }
}


1;
